package com.gosling.cloudspace.common.exception;

import com.gosling.cloudspace.common.constants.CommonConstants;
import com.gosling.cloudspace.common.constants.CommonCodeEnum;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.function.Supplier;

import static com.gosling.cloudspace.common.constants.CommonConstants.FRIENDLY_TIPS;

/**
 * 自定义异常
 *
 * @email
 * @date 20180726
 */
public class CommonException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    private String msg;
    private Integer code = CommonConstants.NO;

    public CommonException() {
        super(FRIENDLY_TIPS);
        this.msg = FRIENDLY_TIPS;
    }

    public CommonException(CommonCodeEnum commonCodeEnum) {
        super(commonCodeEnum.getErrorMessage());
        this.msg = commonCodeEnum.getErrorMessage();
    }

    public CommonException(String msg) {
        super(msg);
        this.msg = msg;
    }

    public CommonException(String msg, Throwable e) {
        super(msg, e);
        this.msg = msg;
    }

    public CommonException(String msg, Integer code) {
        super(msg);
        this.msg = msg;
        this.code = code;
    }

    public CommonException(String msg, Integer code, Throwable e) {
        super(msg, e);
        this.msg = msg;
        this.code = code;
    }

    /**
     * 获取详细的异常信息
     *
     * @param e
     * @return
     */
    public static String detail(Throwable e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }

    public static Supplier<CommonException> tryError(String errorMsg) {
        return () -> new CommonException(errorMsg);
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }


}
